class EmployeesController < ApplicationController
  before_filter :login_required, :authorization_required
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :put, :only => [ :update ], :redirect_to => { :action => :index }
  verify :method => :post, :only => [ :create ], :redirect_to => { :action => :index }
  verify :method => :delete, :only => [ :destroy ], :redirect_to => { :action => :index }
  
  def index
    if params[:query].nil?
      @employees = Employee.find(:all, :order => 'last_name asc, first_name asc')
    else
      @employees = Employee.find(:all, :conditions => ["last_name like ? or first_name like ?", "%#{params[:query]}%", "%#{params[:query]}%"], :order => 'last_name asc, first_name asc')
    end
    respond_to do |format|
      format.html {render :action => 'list.rhtml'}
      format.js {render :action => 'list.rjs'}
      format.xml {render :xml => @employees.to_xml}
    end
  end
  
  def show
    @employee = Employee.find(params[:id])
  end
  
  def new
    @employee = Employee.new
    respond_to do |format|
      format.html {render :action => 'new.rhtml'}
      format.js {render :action => 'new.rjs'}
    end
  end
  
  def create
    @employee = Employee.new(params[:employee])
    if @employee.save
      index
    else
      render :action => 'new' unless request.xhr?
    end
  end
  
  def edit
    @employee = Employee.find(params[:id])
    respond_to do |format|
      format.html {render :action => 'edit.rhtml'}
      format.js {render :action => 'edit.rjs'}
    end
  end
  
  def update
    @employee = Employee.find(params[:id])
    if @employee.update_attributes(params[:employee])
      index
    else
      render :action => 'edit' unless request.xhr?
    end
  end
  
  def destroy
    Employee.find(params[:id]).destroy
    index
  end
end
